package com.alex.core.exception;

import com.alex.core.entity.ApiResponse;
import com.alex.core.enums.ApiResponseEnum;
import com.alex.core.util.ApiResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author cb
 * @date 2019/11/13 14:31
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ApiResponseUtil.failure(ApiResponseEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 接口参数异常捕捉
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse handleBindException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder sb = new StringBuilder();
        fieldErrors.stream().forEach(obj -> sb.append(obj.getField()).append(":").append(obj.getDefaultMessage()).append("|"));
        sb.deleteCharAt(sb.length() - 1);
        return ApiResponseUtil.failure(ApiResponseEnum.PARAM_INVALID.getCode(), String.format("参数无效，具体原因%s", sb.toString()));
    }
}
